#! /usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'jorge.flamarion@gmail.com (Flamarion Jorge)'

import os
import sys
import re
import datetime
import time
import locale

locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
conf_dir = os.path.expanduser('~/.personal-finances')
os.chdir(conf_dir)

#Function to enter expense
def idespesa():
	
	os.system('clear')
	dia = datetime.date.today()
	valord = float(raw_input('\t\tINFORME O VALOR DA DESPESA: '))
	descd = raw_input('\t\tINFORME A DESCRIÇÃO DA DESPESA: ')
	print '\t\tCONFIRMA O VALOR', locale.currency(valord),'DA DESPESA REFERENTE A ',descd,'\n'
	yesno = raw_input('\t\t(S) SIM\t(N)NÃO: ')
	analisa = re.compile('[sSyY]')

	if analisa.match(yesno):
		fd = open('despesas','a')
		fd.write("%s\t%.2f\t%s\n" % (dia, valord, descd))
		fd.close()
		totald = 0
		for i in file('despesas'):
			dia, valord, descd = i.split('\t')
			totald += float(valord)
			fdt = open('total-despesas','w')
			fdt.write('%.2f\n' % (totald))
			fdt.close()
		csaldo()
	else:
		main()

#Function to insert recipe
def ireceita():

	os.system('clear')
	dia = datetime.date.today()
	valorr = float(raw_input('\t\tINFORME O VALOR DA RECEITA: '))
	descr = raw_input('\t\tINFORME A DESCRIÇÃO DA RECEITA: ')
	print '\t\tCONFIRMA O VALOR',locale.currency(valorr),'DA RECEITA REFERENTE A ',descr,'\n'
	yesno = raw_input('\t\t(S) SIM\t(N)NÃO: ')
	analisa = re.compile('[sSyY]')
	
	if analisa.match(yesno):
		fr = open('receitas','a')
		fr.write("%s\t%.2f\t%s\n" % (dia, valorr, descr))
		fr.close()
		totalr = 0
		for i in file('receitas'):
			dia, valorr, descr = i.split('\t')
			totalr += float(valorr)
			frt = open('total-receitas','w')
			frt.write('%.2f\n' % (totalr))
			frt.close()
		csaldo()
	else:
		main()

#Function for list expenses and income
def clancamento():

	os.system('clear')
	print '\t\tRECEITAS\n'
	r = open('receitas','r')
	
	for receitas in r:
		print '\t\t',receitas
	
	print '\t\tDESPESAS\n'
	d = open('despesas','r')
	
	for despesas in d:
		print '\t\t',despesas

#Function for list balance
def csaldo():
	
	os.system('clear')
	arqreceita = open('total-receitas','r')
	arqdespesa = open('total-despesas','r')
	total = 0
	for receita in arqreceita.readlines():
		for despesa in arqdespesa.readlines():
			total = float(receita) - float(despesa)
			arqsaldo = open('saldo','w')
			arqsaldo.write('%.2f\n' % (total))
			arqsaldo.close()
	print '\t\tSALDO ATUAL: ', open('saldo').readline()

#Function to exit gracefully, I think that is dispensable
def sair():
	
	os.system('clear')
	sys.exit(0)

#Main function. Create a menu and files needed to work
def main():
	
	#check if hiden dir ".personal-finances" exists, if not, crete it.
	if not os.path.exists(conf_dir):
		os.makedirs(conf_dir)
		os.chdir(conf_dir)
		#Create files to store data for personal finances if does not exists.
		for i in ['despesas','receitas','saldo','total-despesas','total-receitas']:
			open(i, 'a').close()
	#mount main menu
	print '''	
			OPÇÃO		AÇÃO
			=====		===\n
			D		INSERIR DESPESA
			R		INSERIR RECEITA
			L		CONSULTAR LANÇAMENTOS
			S		CONSULTAR SALDO
			Q		SAIR\n
	'''

	op = raw_input('\t\tSELECIONE UMA OPÇÃO DO MENU: ')
	#parse option. can be better use another method.
	if op == 'L'or op == 'l':
		print '\n'
		clancamento()
	elif op == 'D' or op == 'd':
		print '\n'
		idespesa()
	elif op == 'R' or op == 'r':
		print '\n'
		ireceita()
	elif op == 'S' or op == 's':
		print '\n'
		csaldo()
	elif op == 'Q' or op == 'q':
		print '\n'
		sair()
	else:
		print '\n\t\tOPÇÃO INVÁLIDA.'
		time.sleep(1)
		os.system('clear')
		main()

while True:
	main()
